/*
 * 
 *
 *
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.dao.YiYuanTradeDao;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.YiYuanTrade;
import org.springframework.stereotype.Repository;

import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * Dao - 支付查看答案
 */
@Repository("yiYuanTradeDaoImpl")
public class YiYuanTradeDaoImpl extends BaseDaoImpl<YiYuanTrade, Long> implements YiYuanTradeDao {

    @Override
    public YiYuanTrade findBySn(String sn) {
        if (sn == null) {
            return null;
        }
        String jpql = "select yiyuanTrades from YiYuanTrade yiyuanTrades where lower(yiyuanTrades.sn) = lower(:sn)";
        try {
            return entityManager.createQuery(jpql, YiYuanTrade.class).setFlushMode(FlushModeType.COMMIT).setParameter("sn", sn).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public long isPay(Member member, Long questionId) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<YiYuanTrade> criteriaQuery = criteriaBuilder.createQuery(YiYuanTrade.class);
        Root<YiYuanTrade> root = criteriaQuery.from(YiYuanTrade.class);
        criteriaQuery.select(root);
        Predicate restrictions = criteriaBuilder.conjunction();
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("questionId"), questionId));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("buyer"), member));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("paymentStatus"), YiYuanTrade.PaymentStatus.paid));
        criteriaQuery.where(restrictions);
        return super.count(criteriaQuery, null);
    }
}
